<template>
  <div class="home">
    <div class="operate">
      <input type="button" value="新增" @click="$router.push('addTeacher')" />
      <input type="text" placeholder="请输入关键词" v-model="keyWord" />
      <input type="button" value="查询" @click="queryKeyWord" />
    </div>

    <div class="list">
      <table>
        <thead>
          <tr>
            <th>编号</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>性别</th>
            <th>联系方式</th>
            <th>教学班级</th>
            <th>操作</th>
          </tr>
        </thead>

        <tbody v-if="teachers && teachers.length">
          <tr v-for="teacher in teachers">
            <td>{{ teacher.id }}</td>
            <td>{{ teacher.teacherName }}</td>
            <td>{{ teacher.teacherAge }}</td>
            <td>{{ teacher.teacherSex }}</td>
            <td>{{ teacher.phone }}</td>
            <td>{{ teacher.className }}</td>
            <td>
              <input type="button" value="修改" @click="$router.push(`updateTeacher/${teacher.id}`)" />
              <input type="button" value="删除" @click="del(teacher.id)" />
            </td>
          </tr>
        </tbody>

        <tbody v-else>
          <tr>
            <td colspan="7">暂无数据</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<style scoped>
.operate {
  text-align: center;
  padding: 20px;
}
</style>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'

// 老师列表
const teachers = ref([])

// 后端api
const api = 'http://localhost:8000/teachers'

// 关键词
const keyWord = ref('')

// 查询关键词
function queryKeyWord() {
  // 请求
  axios.get(`${api}?query=${keyWord.value}`).then((res) => {
    if (res.status === 200) {
      teachers.value = res.data.data
    }
  })
}

// 删除请求
function del(id) {
  if (confirm('确认删除')) {
    // 删除请求
    axios.delete(`${api}/${id}`).then((res) => {
      if (res.status === 200) {
        setTimeout(() => {
          // 获取索引
          const index = teachers.value.findIndex((item) => { item.id === id })
          // 删除元素
          teachers.value.splice(index, 1)
        }, 100)
      }
    })
  }
}

onMounted(() => {
  // 请求
  setTimeout(() => {
    axios.get(api).then((res) => {
      if (res.status === 200) {
        teachers.value = res.data.data
      }
    })
  }, 100)
})
</script>
